﻿using Sprout.Repository.Options;
using System;
using System.Collections.Generic;
using System.Data;
using System.Text;

namespace Sprout.Repository
{
    /// <summary>
    /// 事务控制类
    /// </summary>
    internal class TransactionMap
    {
        public TransactionMap(ConnectionSetting connectionSetting, IDbConnection connection)
        {
            if (connection.State == ConnectionState.Closed)
            {
                connection.Open();
            }

            this.ConnectionSetting = connectionSetting;
            this.Transaction = connection.BeginTransaction();
            this.Connection = connection;
            waitExecute = true;
        }

        public ConnectionSetting ConnectionSetting { get; set; }

        public IDbConnection Connection { get; set; }

        public IDbTransaction Transaction { get; set; }

        private bool waitExecute = false;

        /// <summary>
        /// 提交
        /// </summary>
        public void Commit()
        {
            if (waitExecute)
            {
                this.Transaction.Commit();
                this.CloseConnection();
                waitExecute = false;
            }
        }
        /// <summary>
        /// 回滚
        /// </summary>
        public void Rollback()
        {
            if (waitExecute)
            {
                this.Transaction.Rollback();
                this.CloseConnection();
                waitExecute = false;
            }

        }
        /// <summary>
        /// 关闭连接
        /// </summary>
        public void CloseConnection()
        {
            Connection.Close();
            Connection.Dispose();
        }
    }
}
